/**
 * Copyright(c)2012 Beijing PeaceMap Co.,Ltd.
 * All right reserved. 
 */
package com.pmc.dwa.common.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * @description 日期工具类
 * @author aokunsang
 * @date 2013-1-6
 */
public class DateUtils {

	public final static String StepMonth = "month";   //跨越几月
	public final static String StepDay = "day";   //跨越几天
	public final static String StepYear = "year";   //跨越几年
	
	/**
	 * @param dateRegex 日期格式，如：yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	public static String getCurrentDateString(String dateRegex){
		SimpleDateFormat sdf = new SimpleDateFormat(dateRegex);
		return sdf.format(new Date());
	}
	public static String getCurrentDateString(){
		return getCurrentDateString("yyyy-MM-dd HH:mm:ss");
	}
	/**
	 * 格式化日期
	 * @param date
	 * @param dateRegex
	 * @return
	 */
	public static String formatDateString(Date date,String dateRegex){
		if(date==null) return getCurrentDateString("yyyy-MM-dd");
		SimpleDateFormat sdf = new SimpleDateFormat(dateRegex);
		String dateStr = "";
		try {
			dateStr = sdf.format(date);
		} catch (Exception e) {
			dateStr = getCurrentDateString("yyyy-MM-dd");
		}
		return dateStr;
	}
	
	public static String formatDateString(Date date){
		return formatDateString(date,"yyyy-MM-dd HH:mm:ss");
	}
	/**
	 * 通过dateSign获取间隔年月日之后的时间
	 * 默认格式为yyyy-MM-dd HH:mm:ss
	 * @param count
	 * @param date 日期
	 * @param dateRegex 日期格式
	 * @param sign “month”、“day”、“year”  默认为day
	 * @return
	 */
	public static String getDateStringAfterOrBefore(Date selDate,String dateRegex,String sign,int count){
		if(selDate==null) return getCurrentDateString("yyyy-MM-dd");
		String dateString = formatDateString(new Date(),"yyyy-MM-dd");
		String date[] = dateString.split("-");
		Calendar c = GregorianCalendar.getInstance();
		c.set(Integer.parseInt(date[0]),Integer.parseInt(date[1])-1,Integer.parseInt(date[2]));
		if(StepMonth.equalsIgnoreCase(sign)){
			c.add(Calendar.MONTH,count);
		}else if(StepMonth.equalsIgnoreCase(sign)){
			c.add(Calendar.DAY_OF_MONTH,count);
		}else if(StepYear.equalsIgnoreCase(sign)){
			c.add(Calendar.YEAR,count);
		}
		Date dd = c.getTime();
		return formatDateString(dd,dateRegex);
	}
	/**
	 * 获取当前时间的Calendar
	 * @return
	 */
	public static Calendar getCurrentCalendar(){
		Calendar cal = new GregorianCalendar();
		Date date = new Date();
		cal.setTime(date);
		return cal;
	}
}
